package com.UKIT.airtickets.Service.Handlers

import android.content.Context
import android.util.Log
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.Service.FetchJsonData
import com.UKIT.airtickets.Service.JsonData
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.Service.Tikets
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainFragmentHandler(private val context: Context) {

    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    fun loadData(startCity: String, endCity: String, onDataLoaded: (List<Tikets>) -> Unit) {
        coroutineScope.launch {
            val newList = mutableListOf<Tikets>()
            val fetchData = FetchJsonData(object : FetchJsonData.OnDataFetchedListener {
                override fun onDataFetched(data: JsonData?) {
                    data?.let {
                        if (startCity.isEmpty() && endCity.isEmpty()) {
                            onDataLoaded(it.record)
                        } else {
                            for (i in it.record) {
                                if (i.startCity == startCity && i.endCity == endCity) {
                                    newList.add(i)
                                }
                            }
                            onDataLoaded(newList)
                        }
                    } ?: run {
                        Log.e("MainFragmentHandler", "Ошибка при загрузке данных")
                    }
                }
            })
            fetchData.fetchTikets()
        }
    }

    fun getFavoritesFromDatabase(onFavoritesLoaded: (List<Tikets>) -> Unit) {
        coroutineScope.launch {
            val userFavoriteDao = AppDatabase.getDatabase(context).userFavoriteDao()
            val favorites = userFavoriteDao.getUserFavorites(SettingsApp.userId.toLong())
            val favoriteTickets = favorites.map { favorite ->
                Tikets(
                    searchToken = favorite.searchToken,
                    startCity = favorite.startCity,
                    startCityCode = favorite.startCityCode,
                    endCity = favorite.endCity,
                    endCityCode = favorite.endCityCode,
                    startDate = favorite.startDate,
                    endDate = favorite.endDate,
                    price = favorite.price
                )
            }
            onFavoritesLoaded(favoriteTickets)
        }
    }
}
